﻿using System;
using System.Text.RegularExpressions;

namespace DotNetNuke.Modules.UserDefinedTable
{



  public class CSVReader
  {



    public static string[] DecodeCSV(string strLine)
    {
        Match objMatch;

        // build a pattern
        string strPattern = @"^"
            + @"(?:""(?<value>(?:""""|[^""\f\r])*)""|(?<value>[^,\f\r""]*))"
            + @"(?:,(?:[ \t]*""(?<value>(?:""""|[^""\f\r])*)""|(?<value>[^,\f\r""]*)))*"
            + @"$"; // anchor to the end of the string

        //get the match
        objMatch = Regex.Match(strLine, strPattern);

        //if RegEx match was ok
        if(objMatch.Success)
        {
            Group objGroup = objMatch.Groups["value"];
            int intCount = objGroup.Captures.Count;
            string[] arrOutput = new string[intCount - 1];

            //transfer data to array
            for (int i = 0 ; i < intCount; i++)
            {
                Capture objCapture = objGroup.Captures[i];
                arrOutput[i] = objCapture.Value;

                //replace double-escaped quotes
                arrOutput[i] = arrOutput[i].Replace("\"\"", "\"");
            }

            //return the array
            return arrOutput;
        }
        else
            throw new Exception(String.Format("Wrong CSV line: {0}", strLine));

    }


  }

}
